package com.yunxin.download.server.infra.support.task;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.yunxin.download.server.infra.constant.FileExportConstant;
import com.yunxin.download.server.infra.constant.enums.DownloadFileStatusEnum;
import com.yunxin.download.server.infra.repository.DownloadRecordDao;
import com.yunxin.download.server.infra.utils.DateUtils;
import com.yunxin.download.server.infra.utils.SpringContextUtils;
import com.yunxin.download.server.model.entity.DownloadRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.net.URL;
import java.util.Date;
import java.util.function.Supplier;
/**
 * @author zero°
 * @since 2023-06-15
 */
@Slf4j
public class ExportAsyncTask implements Runnable {

    private final Supplier<String> exportHandle;
    private final DownloadRecordDao downloadRecordDao;
    private final DownloadRecord downloadRecord;
    private final String dataSourceLookupKey;


    /**
     * @param dataSourceName dataSourceName
     * @param exportHandle exportHandle
     * @param downloadRecordDao downloadRecordDao
     * @param downloadRecord downloadRecordDao
     */
    public ExportAsyncTask(String dataSourceName, Supplier<String> exportHandle,
                           DownloadRecordDao downloadRecordDao, DownloadRecord downloadRecord) {
        this.exportHandle = exportHandle;
        this.downloadRecordDao = downloadRecordDao;
        this.downloadRecord = downloadRecord;
        this.dataSourceLookupKey = dataSourceName;

    }

    @Override
    public void run() {
        try {
            //设置当前线程使用的数据源
            DynamicDataSourceContextHolder.push(dataSourceLookupKey);
            //获取导出生成的oss
            ApplicationContext applicationContext = SpringContextUtils.getApplicationContext();
            //直接使用  不判断空了如果没有就报错了
            String endpoint = applicationContext.getEnvironment().getProperty("aliYun.oss.endpoint");
            String accessKeyId = applicationContext.getEnvironment().getProperty("aliYun.oss.accessKeyId");
            String accessKeySecret = applicationContext.getEnvironment().getProperty("aliYun.oss.accessKeySecret");
            String bucket = applicationContext.getEnvironment().getProperty("aliYun.oss.bucket");

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            String ossKey = exportHandle.get();
            Date date = DateUtils.X.addDay(new Date(), FileExportConstant.FILE_EXPIRE_DAY_NUM);
            //生成oss下载地址  限制过期时间
            URL url = ossClient.generatePresignedUrl(bucket, ossKey, date);

            ossClient.shutdown();

            downloadRecord.setOssKey(ossKey);
            downloadRecord.setDownloadFileUrl(url.toString());
            downloadRecord.setEditTime(new Date());
            downloadRecord.setDownloadFileStatus(DownloadFileStatusEnum.CREATE_SUCCESS.getStatus());
        } catch (Exception e) {
            log.error("导出失败 " + Thread.currentThread().getName(), e);
            downloadRecord.setEditTime(new Date());
            downloadRecord.setDownloadFileStatus(DownloadFileStatusEnum.CREATE_FAIL.getStatus());
        } finally {
            //清理掉当前设置的数据源，让默认的数据源不受影响
            DynamicDataSourceContextHolder.clear();
            //执行更新
            downloadRecordDao.updateByPrimaryKeySelective(downloadRecord);
        }
    }
}
